/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.server.handler;

import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.server.common.RuntimeEnv;
import cn.ac.iie.di.wx.server.httpservice.HttpSender;
import cn.ac.iie.di.wx.server.utils.TimeStampUtil;
import cn.ac.iie.di.wx.server.vo.OracleUpdateVo;
import cn.ac.iie.di.wx.server.vo.RedisVo;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class OCRHandler_1 implements HandlerI {

    static Logger logger = Logger.getLogger(OCRHandler_1.class.getName());

    @Override
    public void init() throws Exception {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String overSeaAccountQuery = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
        logger.info("receive OCRHandler_1 request:" + overSeaAccountQuery);
        //解析请求，获取请求业务编号id,若请求得到成功响应，则到指定文件夹下获取相应的json文件，从该文件获取布控的结果
        try {
            JSONObject addGroupMonitorJson = JSONObject.parseObject(overSeaAccountQuery);
            String opid = addGroupMonitorJson.getString("opid");//存redis里，将关键字存value里面
            String param = addGroupMonitorJson.getString("param");
            //将系统参数补全
            addGroupMonitorJson.put("areaid", (String) RuntimeEnv.getParam(RuntimeEnv.areaid));
            addGroupMonitorJson.put("userareaid", (String) RuntimeEnv.getParam(RuntimeEnv.userareaid));
            addGroupMonitorJson.put("sysid", (String) RuntimeEnv.getParam(RuntimeEnv.sysid));
            addGroupMonitorJson.put("sysuserid", (String) RuntimeEnv.getParam(RuntimeEnv.sysuserid));
            logger.info(addGroupMonitorJson.toJSONString());
            //
            String themes = addGroupMonitorJson.getString("themes");
            String topics = addGroupMonitorJson.getString("topics");
            if (themes == null || topics == null) {
                logger.info("themes or topics is null");//不存在这两个字段，则不需要作移除
            } else {
                int themes_val = Integer.parseInt(themes);
                int topics_val = Integer.parseInt(topics);
                addGroupMonitorJson.remove("themes");
                addGroupMonitorJson.remove("topics");
                logger.info("remove themes and topics ,the json is :"+addGroupMonitorJson.toJSONString());
                if (themes_val==-1||topics_val==-1) {
                    RuntimeEnv.redisVos.put(new RedisVo(opid, "-1"));
                }else{
                    RuntimeEnv.redisVos.put(new RedisVo(opid, themes_val+"_"+topics_val));
                }
                
            }

            //获取两者的值，进行判断是否是数字格式的字符串
            //存入redis,如果都为-1，则存为-1，否则存为主题值_专题值
            //新增主题专题区分字段
            //获取响应,post，请求格式和发送方法
            HttpSender hs = new HttpSender();
            String responseStr = hs.closableHttpClient(addGroupMonitorJson.toJSONString(), (String) RuntimeEnv.getParam(RuntimeEnv.OCRQuery));
            //若frontnum=0，则表示请求已经处理完成

//        String responseStr = "{\"opid\": \"020004\",\"msgid\": \"123456\",\"frontnum\": 0,\"status\": \"200\"}";
            //解析响应
            if (responseStr.equals("")) {
                //失败情况
                logger.info("OCRHandler_1 response is null");
                responseStr="{\"opid\": \""+opid+"\",\"desc\": \"response is null\",\"frontnum\": -1,\"status\": \"404\"}";;
            } else {
                logger.info("OCRHandler_1 response is sucess:" + responseStr);
                try {
                    JSONObject jSONObject = JSONObject.parseObject(responseStr);
                    String frontnum = jSONObject.getString("frontnum");
                    String status = jSONObject.getString("status");
                    if (status.equals("200")) {
                        //状态正常
                        if (frontnum.equals("0")) {
                            //若为0，则表示已经处理完，生成了json文件，和布控结果文件zip，这三种文件会推送至指定文件夹下
                            //解析json获取文件名信息
                            //正确返回
                            //添加oracle入库，记录返回时间-6.5
                            logger.info("OCRHandler_1 response is 200");
                            logger.info(Long.parseLong(opid));

                            long timestamp = TimeStampUtil.nextId();
                            logger.info(timestamp);
                            logger.info(new Timestamp(timestamp));
                            RuntimeEnv.oracleUpdateQueue.add(new OracleUpdateVo(Long.parseLong(opid), new Timestamp(timestamp), "OCR"));
                        } else {
                            logger.info("OCR该业务正在排队中");
                        }
                    } else {
                        logger.info("OCR业务请求状态不正常");
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            //给客户端发送响应消息
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            InputStream inputStream = new ByteArrayInputStream(responseStr.getBytes("UTF-8"));
            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                bos.write(bytesContent, 0, bytesReadIn);
            }
            RuntimeEnv.OCRCount.getAndIncrement();
            bos.flush();
            bos.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
